//
//  SEGPayListViewController.m
//  ExcellentHome
//
//  Created by 陈区 on 14-11-4.
//  Copyright (c) 2014年 陈区. All rights reserved.
//
#import "SEGPayListViewController.h"
#import "SEGDidPaidViewController.h"


@interface SEGPayListViewController ()
@property(nonatomic, strong) SEGCommonPayViewModel *viewModel;

@end

@implementation SEGPayListViewController

#pragma mark - life cycle
- (instancetype)initWithViewModel:(SEGCommonPayViewModel*)viewModel{
    if (self == [super init]) {
        _viewModel = viewModel;
    }
    return self;
}

- (void)loadView
{
    UIScreen* scr = [UIScreen mainScreen];

    CGRect appbounds = CGRectMake(0, 0, scr.bounds.size.width, scr.bounds.size.height - kNavigationBarAndStatusBarHeight);
    UIView* mainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, appbounds.size.width, appbounds.size.height)];

    m_tableView = [[UITableView alloc] initWithFrame:appbounds style:UITableViewStylePlain];
    m_tableView.backgroundColor = [UIColor clearColor];
    m_tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    m_tableView.delegate = self;
    m_tableView.dataSource = self;

    [mainView addSubview:m_tableView];

    self.view = mainView;
}

- (void)viewDidLoad {

    [super viewDidLoad];
    self.title = @"支付方式";
    [self showCustomNavigationBackButton];
}

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];
    if ([WXApi isWXAppInstalled]) // 判断 用户是否安装微信
    {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getOrderPayResult:) name:@"ORDER_PAY_NOTIFICATION" object:nil]; //监听一个通知
    }

    [self segInitViews];
    [self bindViewModel];
}

- (void)viewWillDisappear:(BOOL)animated
{

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 通知信息
/// 微信支付成功后触发的通知
- (void)getOrderPayResult:(NSNotification*)notification {
    
    if ([notification.object isEqualToString:@"success"]) {
        
        if (self.viewModel.payTypeName == SEGPayTypeName_WashCar) { //洗车成功界面
            NSDictionary *params = @{@"orderSid":self.viewModel.orderIdOracctItemIds};
            UIViewController *webVC = [[SEGUhomeMediator sharedInstance]seg_initWashingCarFinishViewController:params];
            [self pushToCurrentViewController:webVC];
        }
        else{//支付成功页面
            SEGDidPaidViewController* pay = [[SEGDidPaidViewController alloc] initWithViewModel:self.viewModel.didPaidViewModel];
            [self.navigationController pushViewController:pay animated:YES];
        }
    }
}



#pragma mark - tableview datasource

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.viewModel.listData.count;
}

- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    return 59;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    NSString* cellIdentifier = @"cell";

    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.backgroundColor = kColor_W;

        UIView* grayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 14)];
        grayView.backgroundColor = kColor_bg;
        [cell.contentView addSubview:grayView];
        

        UIImageView* line1ImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 14, tableView.frame.size.width, 0.5)];
        line1ImgView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"line_640.png")];
        [cell.contentView addSubview:line1ImgView];
        

        UIImageView* payIcon = [[UIImageView alloc] initWithFrame:CGRectMake(20, 10 + 15, 40, 25)];
        payIcon.tag = 1000;
        payIcon.contentMode = UIViewContentModeScaleAspectFit;
        [cell.contentView addSubview:payIcon];
        

        UILabel* lbName = [[UILabel alloc] initWithFrame:CGRectMake(payIcon.frame.origin.x + payIcon.frame.size.width + 20, 15, 300, 44)];
        lbName.textColor = kColor_1;
        lbName.backgroundColor = [UIColor clearColor];
        lbName.textAlignment = NSTextAlignmentLeft;
        lbName.adjustsFontSizeToFitWidth = YES;
        lbName.font = [UIFont systemFontOfSize:FONT_LIST_AND_DETAIL_SIZE];
        lbName.tag = 1001;
        [cell.contentView addSubview:lbName];
        

        UIImageView* line2ImgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 58, tableView.frame.size.width, 0.5)];
        line2ImgView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"line_640.png")];
        [cell.contentView addSubview:line2ImgView];
        
    }

    NSDictionary* dic = [self.viewModel.listData objectAtIndex:indexPath.row];

    UIImageView* payIcon = (UIImageView*)[cell.contentView viewWithTag:1000];
    UILabel* lbName = (UILabel*)[cell.contentView viewWithTag:1001];

    [payIcon setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", [dic objectForKey:@"iconUrl"]]] placeholderImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_70_70")]];
    lbName.text = [dic objectForKey:@"name"];

    return cell;
}

#pragma mark - tableview Delegate

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary* dic = [self.viewModel.listData objectAtIndex:indexPath.row];
    [self.viewModel.confirmPayStatusCommand execute:dic];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Init Views
-(void)segInitViews{}

#pragma mark - Layout
- (void)updateViewConstraints {
    [super updateViewConstraints];
}

#pragma mark - Private Methods

/// push VC
/// @param vc vc
-(void)pushToCurrentViewController:(UIViewController*)vc {
    
    NSMutableArray *vcArr = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
    
    for (NSInteger i = vcArr.count -1; i >= 0; i --) {
        UIViewController *indexVC = vcArr[i];
        
        if ([NSStringFromClass(indexVC.class) isEqualToString:NSStringFromClass(self.class)]) {
            [vcArr removeObjectAtIndex:i];
        }
    }
    
    [vcArr addObject:vc];
    [self.navigationController setViewControllers:vcArr animated:YES];
}

- (void)onNavigationLeftButtonClicked:(UIButton*)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - RAC Data Binding
- (void)bindViewModel {
    
    @weakify(self);
    
    [[[self.viewModel.confirmPayStatusCommand executionSignals] switchToLatest] subscribeNext:^(NSDictionary*  _Nullable x) {
        
        @strongify(self)
        
        if (x && [x isKindOfClass:[NSDictionary class]]) {
            
            if ([[x valueForKey:@"payMethod"] isEqualToString:@"4"]) { //货到付款
                [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:2]
                                                      animated:YES];
                UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:[x valueForKey:@"messaage"] delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil];
                [alertView show];
            }
            
        }
        
    }];
    
    [[[self.viewModel.freshUICommand executionSignals] switchToLatest] subscribeNext:^(id  _Nullable x) {
        
        @strongify(self)
        

        [self->m_tableView reloadData];
    }];
    
    [self.viewModel.messageSubject subscribeNext:^(NSString*  _Nullable x) {
        [SEGAlertView showTmepMessageWithMessage:x];
    }];
    
    [self.viewModel.freshUICommand execute:nil];

}



#pragma mark - getter
-(SEGCommonPayViewModel *)viewModel{
    if (!_viewModel) {
        _viewModel = [[SEGCommonPayViewModel alloc]init];
    }
    return _viewModel;
}
#pragma mark setter
@end
